package com.xiran.mointer.service;


import com.xiran.mointer.model.SystemMetrics;
import org.springframework.stereotype.Service;
import oshi.SystemInfo;
import oshi.hardware.CentralProcessor;
import oshi.hardware.GlobalMemory;
import oshi.hardware.HardwareAbstractionLayer;
import oshi.util.Util;

@Service
public class SystemMonitorService {

    private final SystemInfo systemInfo = new SystemInfo();
    private final HardwareAbstractionLayer hardware = systemInfo.getHardware();
    private final CentralProcessor processor = hardware.getProcessor();
    private long[] prevTicks = null;

    public SystemMetrics getSystemMetrics() {
        // CPU 使用率
        long[] ticks = processor.getSystemCpuLoadTicks();
        if (prevTicks == null) {
            // 第一次调用，等待一点时间
            Util.sleep(500);
            ticks = processor.getSystemCpuLoadTicks();
        }
        long[] prev = prevTicks != null ? prevTicks : ticks;
        long user = ticks[CentralProcessor.TickType.USER.getIndex()] - prev[CentralProcessor.TickType.USER.getIndex()];
        long nice = ticks[CentralProcessor.TickType.NICE.getIndex()] - prev[CentralProcessor.TickType.NICE.getIndex()];
        long sys = ticks[CentralProcessor.TickType.SYSTEM.getIndex()] - prev[CentralProcessor.TickType.SYSTEM.getIndex()];
        long idle = ticks[CentralProcessor.TickType.IDLE.getIndex()] - prev[CentralProcessor.TickType.IDLE.getIndex()];
        long iowait = ticks[CentralProcessor.TickType.IOWAIT.getIndex()] - prev[CentralProcessor.TickType.IOWAIT.getIndex()];
        long irq = ticks[CentralProcessor.TickType.IRQ.getIndex()] - prev[CentralProcessor.TickType.IRQ.getIndex()];
        long soft = ticks[CentralProcessor.TickType.SOFTIRQ.getIndex()] - prev[CentralProcessor.TickType.SOFTIRQ.getIndex()];
        long steal = ticks[CentralProcessor.TickType.STEAL.getIndex()] - prev[CentralProcessor.TickType.STEAL.getIndex()];

        long total = user + nice + sys + idle + iowait + irq + soft + steal;
        double cpuUsage = total > 0 ? (double) (user + nice + sys + iowait + irq + soft) / total : 0;
        prevTicks = ticks;

        // 内存
        GlobalMemory memory = hardware.getMemory();
        long totalMemory = memory.getTotal();
        long availableMemory = memory.getAvailable();
        double memoryUsage = (double) (totalMemory - availableMemory) / totalMemory;

        // 磁盘（使用根目录）
        String diskPath = "/";
        java.io.File file = new java.io.File(diskPath);
        long totalSpace = file.getTotalSpace();
        long usedSpace = totalSpace - file.getUsableSpace();
        double diskUsage = totalSpace > 0 ? (double) usedSpace / totalSpace : 0;

        SystemMetrics metrics = new SystemMetrics();
        metrics.setCpuUsage(cpuUsage);
        metrics.setMemoryUsage(memoryUsage);
        metrics.setDiskUsage(diskUsage);
        metrics.setTimestamp(System.currentTimeMillis());
        return metrics;
    }
}